package com.mvc.controller;

import com.mvc.pojo.Student;
import com.mvc.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("list.html")
    public String list(Model model) {
        List<Student> studentList = studentService.getAllStudent();
        model.addAttribute("studentList", studentList);
        return "list";
    }

    @RequestMapping("add.html")
    public String add(Student student, HttpServletRequest request) {
        if (student.getId() == 1) {
            request.setAttribute("message", "学号已存在");
            return "add";
        }
        studentService.addStudent(student);
        return "redirect:list.html";
    }

    @RequestMapping("check.html")
    public ModelAndView check(String name) {
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Map<String, Object> result = new HashMap<>();
        if ("张三".equals(name)) {
            result.put("msg", "姓名已存在");
            result.put("status", false);
        } else {
            result.put("msg", "姓名可以使用");
            result.put("status", true);
        }
        return new ModelAndView(view,  result);
    }
}
